<template>
  <div class="wx_fansManage">
    <div class="search-condition">
      <el-form :inline="true">
        <el-row>
          <el-form-item>
            <el-col :span="21">
              <el-input placeholder="昵称搜索" v-model="searchForm.wd" @keyup.enter.native="submitSearch"></el-input>
            </el-col>
            <el-col :span="3"><el-button style="margin-left:10px" @click="submitSearch">搜索</el-button></el-col>
          </el-form-item>
        </el-row>
        <!-- <el-form-item label="关注状态">
          <el-select v-model="form.subscribeStatus">
             <el-option v-for="item in form.subscribeStatusOption"
               :key="item.value"
               :label="item.label"
               :value="item.value"
             >
             </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="标签">
          <el-select v-model="form.tag" clearable>
            <el-option v-for="item in tagList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关注/取消时间">
          <el-date-picker
            v-model="form.subscribeTimeRange"
            type="datetimerange"
            placeholder="选择日期时间"
            format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
          <!-- <el-date-picker
            v-model="form.subscribeTimeEnd"
            type="datetime"
            placeholder="选择日期时间"
            format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker> -->
        </el-form-item>
      </el-form>
    </div>
    <el-row>
      <el-col :span="8">
        <el-button @click="addTagDialog">添加标签</el-button>
        <el-button @click="addToblack">加入黑名单</el-button>
        <el-button @click="syncUpdate">重新同步</el-button>
        <div class="tagPanel" v-show="showTagDialog">
          <i class="poper-arrow-out"></i>
          <i class="poper-arrow-in"></i>
          <div class="tages">
            <el-checkbox-group v-model="checklist" >
              <template v-for="item in tagList">
                <el-checkbox :label="item.id" :key="item.id" :value="item.id" :title="item.name">{{item.name}}</el-checkbox>
              </template>
            </el-checkbox-group>
          </div>
          <div class="tagBottom">
            <el-button type="primary" @click="tagConfirm" :loading="loading">确定</el-button>
            <el-button @click="tagCancel">取消</el-button>
          </div>
        </div>
      </el-col>
      <el-col :span="10" v-if="flag">
        <el-progress :text-inside="true" :stroke-width="18" :percentage="percentage" status="success"></el-progress>
      </el-col>
      <el-col :span="flag?6:16" style="text-align:right;">
        <el-button type="text" @click="tagsDialogOpen()">微信标签管理</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="tbLoading" element-loading-text="拼命加载中" :data="fansList.list" @selection-change="handleSelectionChange" stripe class="table">
      <el-table-column prop="openid" type="selection" width="55" className="is-center">
      </el-table-column>
      <el-table-column label="头像" className="is-center">
        <template slot-scope="scope">
         <img :src="scope.row.headimgurl" alt="" class="avatar">
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label="昵称" className="is-center">
      </el-table-column>
      <el-table-column prop="tagidList" label="标签" className="is-center" min-width="240">
        <template slot-scope="scope">
          {{scope.row.tagidList?getTagNames(scope.row.tagidList):'无标签'}}
          <el-popover
            placement="bottom"
            width="300"
            trigger="click"
            popper-class="wx_fans_tag_pop"
            @show="showAddUserTag(scope.row.tagidList)">
            <i class="el-icon-caret-bottom" slot="reference"></i>
            <div class="tagsWrap" v-if="scope.row.tagidList">
              <el-tag
                v-for="tag,n in getTagNames(scope.row.tagidList).split('，')"
                :key="n.toString()"
                :closable="true"
                type="primary"
                @close="handleDelTag(scope.row, scope.row.tagidList.split(',')[n], scope.row.openid)"
              >
              {{tag}}
              </el-tag>
            </div>
            <div style="font-size:14px;">添加标签：</div>
            <el-select v-model="addTagId">
              <el-option v-for="item in tagListCopy"
                         :key="item.id"
                         :label="item.name"
                         :value="item.id"
                         :disabled="item.disabled"
              ></el-option>
            </el-select>
            <el-button type="primary" @click="addUserTag(scope.row, scope.row.openid)" :loading="loading">确定</el-button>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="关注/取消时间" className="is-center" width="180">
        <template slot-scope="scope">
           <div>{{$date.format(scope.row.subscribeTime*1000, 'YYYY-MM-DD HH:mm:ss')}}</div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        :current-page.sync="page"
        :page-size.sync="size"
        layout="sizes, total, prev, pager, next, jumper"
        :page-sizes="[10, 30, 50, 100]"
        :total="fansList.page.total"
        @current-change="submitSearch()"
        @size-change="handleSizeChange">
      </el-pagination>
    </div>
    <el-dialog
      title="微信标签管理"
      width="30%"
      :visible.sync="dialog"
      custom-class="dialog_tags">
      <el-col :span="14">
        <el-input v-model="wd2">
          <el-button slot="append" @click="handleSearchTag">搜索</el-button>
        </el-input>
      </el-col>
      <el-col :span="4" :push="1">
        <el-button type="text" @click="addNewAttr">新建标签</el-button>
      </el-col>
      <el-table 
        element-loading-text="拼命加载中"
        :data="tagList" 
        stripe
        height="250"
        class="table">
        <el-table-column prop="name" label="标签名称"></el-table-column>
        <el-table-column label="操作" className="is-center" width="100">
          <template slot-scope="scope">
            <el-button type="text" @click="delTag(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialog = false">关闭</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="新建标签"
      width="30%"
      :visible.sync="dialogNewAttr"
      class="newattr_wrap">
      <el-input v-model="newTag" placeholder="请输入标签"></el-input>
      <el-button type="primary" @click="handleCreateTag">确定</el-button>
    </el-dialog>
  </div>
</template>
<script>
  import {mapState, mapActions, mapMutations} from 'vuex'
  import ElRow from 'element-ui/packages/row/src/row'
  export default {
    components: {ElRow},
    data () {
      return {
        appid: null,
        searchForm: {
          wd: ''
        },
        tbLoading: true,
        page: 1,
        size: 10,
        form: {
          tag: '',
          subscribeStatus: '',
          subscribeTimeRange: null,
          subscribeTimeStart: null,
          subscribeTimeEnd: null,
          subscribeStatusOption: [
            {
              label: '不限',
              value: ''
            },
            {
              label: '关注',
              value: '1'
            },
            {
              label: '不关注',
              value: '0'
            }]
        },
        newTag: '',
        wd2: '',
        addTagId: null,
        checklist: [], // 所有标签选中的Id
        show: true, // 是否显示新建标签，默认显示新建标签不显示文本框
        showTagDialog: false, // 默认不显示
        multipleSelection: [], // 表格选中的行
        percentage: 0.00,
        flag: false, // 进度条的显示
        loading: false,
        dialog: false,
        dialogNewAttr: false,
        delScopeTag: [],
        tagListCopy: []
      }
    },
    computed: {
      ...mapState({
        fansList: state => state.wxfansList.fansList,
        tagList: state => state.wxfansList.tagsList
      }),
      mapTagIdToName () {
        const obj = {}
        for (let i in this.tagList) {
          obj[this.tagList[i].id] = this.tagList[i].name
        }
        return obj
      }
    },
    mounted () {
      this.initPageData()
    },
    destroyed () {
      clearInterval(this.inteval)
    },
    methods: {
      ...mapActions(['getFansList', 'getwxTagList', 'addwxTag', 'delWxTag', 'addwxTagToUser', 'addwxToBlack', 'triggerUpdateFan', 'asyncUpdateFans']),
      ...mapMutations(['SET_WXTAGLIST']),
      // 初始化页面数据
      async initPageData () {
        this.appid = this.$route.params.appid
        this.submitSearch()
        this.getProsses()
        await this.getFansTagList()
        this.allTags = this.tagList
      },
      initTable () {
        this.submitSearch()
          .finally((res) => { this.tbLoading = false })
      },
      // 粉丝列表查询
      submitSearch (showLoading = true) {
        showLoading && (this.tbLoading = true)
        console.log(showLoading, this.tbLoading)
        this.getFansList({
          wd: this.searchForm.wd,
          appid: this.appid,
          subscribeStatus: this.form.subscribeStatus,
          tagId: this.form.tag,
          subscribeTimeStart: this.form.subscribeTimeRange && this.form.subscribeTimeRange[0] && this.$date.format(this.form.subscribeTimeRange[0], 'YYYY-MM-DD hh:mm:ss'),
          subscribeTimeEnd: this.form.subscribeTimeRange && this.form.subscribeTimeRange[1] && this.$date.format(this.form.subscribeTimeRange[1], 'YYYY-MM-DD hh:mm:ss'),
          page: this.page,
          size: this.size
        }).then(res => {
          this.tbLoading = false
        })
      },
      // 获取粉丝标签列表
      async getFansTagList () {
        await this.getwxTagList(this.appid)
      },
      // 获取分时标签对应的名称
      getTagNames (tags) {
        if (tags) {
          let str = ''
          const tagArr = tags && tags.split(',')
          tagArr.forEach((item, n) => {
            str += this.mapTagIdToName[item] + '，'
          })
          str = str.slice(0, -1)
          return str
        }
      },
      // 改变分页大小
      handleSizeChange (size) {
        this.size = size
        this.submitSearch()
      },
      /* 表格行选择 */
      handleSelectionChange (val) {
        this.multipleSelection = val
      },
      /* 新建标签 */
      async handleCreateTag () {
        const res = await this.addwxTag({
          appid: this.appid,
          tagName: this.newTag
        })
        this.getFansTagList()
        if (res.data.code === 1) {
          this.$message.success('添加成功')
          this.dialogNewAttr = false
        }
      },
      cancelTag () {
        this.show = true
      },
      // 打开添加标签对话框
      addTagDialog () {
        this.checklist = []
        this.showTagDialog = true
      },
      // 加入黑名单
      addToblack () {
        if (this.multipleSelection.length <= 0) {
          this.$message({
            type: 'warning',
            message: '你还没选择用户!'
          })
          return
        }
        this.$confirm('加入黑名单后，你将无法接收该用户发来的消息，且该用户无法接收公众号发出的消息，无法参与留言和赞赏，确认加入黑名单？', '提示')
          .then(() => {
            this.addwxToBlack({
              appid: this.appid,
              status: 1,
              openids: this.multipleSelection.map(obj => obj.openid)
            }).then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
                this.submitSearch()
              } else {
                this.$message({
                  type: 'error',
                  error: res.data.msgZ
                })
              }
            })
          })
      },
      /* 同步更新 */
      syncUpdate () {
        this.triggerUpdateFan({
          appid: this.appid
        }).then(res => {
          if (res.data.code === 1) {
            this.getProsses()
          }
        })
      },
      /* 获取同步更新进度 */
      getProsses () {
        this.inteval = setInterval(() => {
          this.asyncUpdateFans({
            appid: this.appid
          }).then(res => {
            if (res.data.data.totel === 0) {
              this.$message.warning('没有粉丝数据')
              clearInterval(this.inteval)
              return false
            }
            if (res.data.data.cleanProgress / res.data.data.totel >= 1) {
              this.percentage = 100
              this.flag = false
              clearInterval(this.inteval)
            } else {
              let percent = res.data.data.cleanProgress / res.data.data.totel
              this.percentage = parseFloat(percent * 100).toFixed(2) - 0.00
              this.flag = true
            }
          })
        }, 1000)
      },
      /* 给用户打标签 */
      async tagConfirm () {
        if (this.multipleSelection.length === 0) {
          this.$message({
            type: 'warning',
            message: '请选择添加标签的用户对象!'
          })
          return
        }
        this.loading = true
        const res = await this.addwxTagToUser({
          appid: this.appid,
          tagId: this.checklist,
          openIds: this.multipleSelection.map(obj => obj.openid)
        })
        this.loading = false
        if (res.data.code === 1) {
          this.$message({
            type: 'success',
            message: '添加成功!'
          })
          this.showTagDialog = false
          this.checklist = []
          this.submitSearch()
          // this.multipleSelection.forEach(item => {
          //   if (!item.tagidList) {
          //     item.tagidList = ''
          //   }
          //   for (let i = 0, length = this.checklist.length; i < length; i++) {
          //     item.tagidList += ',' + this.checklist[i]
          //   }
          //   if (item.tagidList.substring(0, 1) === ',') {
          //     item.tagidList = item.tagidList.substring(1)
          //   }
          // })
          // this.multipleSelection = []
        }
      },
      /* 关闭打标签对话框 */
      tagCancel () {
        this.showTagDialog = false
      },
      // 删除用户标签
      async handleDelTag (rowData, tagId, openId) {
        if (this.delScopeTag.indexOf(tagId) >= 0) {
          return
        }
        this.delScopeTag.push(tagId)
        const res = await this.addwxTagToUser({
          appid: this.appid,
          tagId: [+tagId],
          openIds: [openId],
          op: 'untagged'
        })
        if (res.data.code === 1) {
          this.$message.success('删除成功')
          this.submitSearch()
          const index = rowData.tagidList.split(',').indexOf(tagId)
          const tagArr = rowData.tagidList.split(',')
          tagArr.splice(index, 1)
          rowData.tagidList = tagArr.join(',')
          this.delScopeTag.splice(this.delScopeTag.indexOf(tagId), 1)
        }
      },
      // 给单个用户添加标签显示时
      showAddUserTag (tags) {
        this.addTagId = null
        let tagsArr = tags && tags.split(',')
        let tagListCopy = this.tagList.slice()
        tagListCopy.map(item => {
          if (tagsArr && tagsArr.indexOf(item.id + '') > -1) {
            item.disabled = true
          } else {
            item.disabled = false
          }
        })
        this.tagListCopy = tagListCopy
      },
      // 给单个用户添加标签
      async addUserTag (rowData, openid) {
        if (this.addTagId === null) {
          this.$message({
            type: 'warning',
            message: '请选择添加的标签！'
          })
          return
        }
        this.loading = true
        const res = await this.addwxTagToUser({
          appid: this.appid,
          tagId: [this.addTagId],
          openIds: [openid]
        })
        this.loading = false
        if (res.data.code === 1) {
          this.$message.success('添加成功')
          this.submitSearch()
          rowData.tagidList += ',' + this.addTagId
          this.showAddUserTag(rowData.tagidList)
        }
      },
      // 删除标签
      async delTag (id) {
        const res = await this.delWxTag({
          appid: this.appid,
          tagId: [id]
        })
        if (res.data.code === 1) {
          this.$message.success('删除成功')
          this.getFansTagList()
          this.submitSearch(false)
        }
      },
      // 搜索标签
      async handleSearchTag () {
        await this.getFansTagList()
        const filterArr = this.tagList.filter(item => {
          return item.name.indexOf(this.wd2) !== -1
        })
        this.SET_WXTAGLIST(filterArr)
      },
      // 微信标签管理
      tagsDialogOpen () {
        this.dialog = true
        this.wd2 = ''
      },
      // 新建标签按钮点击
      addNewAttr () {
        this.dialogNewAttr = true
        this.newTag = ''
      }
    }
  }
</script>
<style lang="scss">
  .wx_fansManage{
    .main{overflow: initial}
    .avatar{margin-right:3px;width:32px;height:32px;border-radius:50%;vertical-align:middle;}
    .el-progress{line-height:2;}
    .tagPanel{
      position:absolute;
      width:400px;
      border:1px solid #d9dadc;
      margin-top:8px;
      z-index:9;
      background-color:#fff;
      .el-checkbox {width:100px;margin-left:0;margin-right: 15px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
    }
    .tagPanel .poper-arrow-out{
      position: absolute;
      left: 40px;
      margin-left: -8px;
      margin-top: -8px;
      display: inline-block;
      width: 0;
      height: 0;
      border-width: 8px;
      border-style: dashed;
      border-color: transparent;
      border-top-width: 0;
      border-bottom-color: #d9dadc;
      border-bottom-style: solid;
    }
    .tagPanel .poper-arrow-in{
      position: absolute;
      left: 40px;
      top:1px;
      margin-left: -8px;
      margin-top: -8px;
      display: inline-block;
      width: 0;
      height: 0;
      border-width: 8px;
      border-style: dashed;
      border-color: transparent;
      border-top-width: 0;
      border-bottom-color: #fff;
      border-bottom-style: solid;
    }
    .tagPanel .tages{
      max-height:240px;
      overflow-y:auto;
      padding:20px 20px 0 20px;
    }
    .tagPanel .editTag{margin: 10px 0 0 20px;}
    .tagPanel .tagBottom{
       border-top:1px solid #d9dadc;
       padding:20px 30px;
       text-align: center;
    }
    .el-table{
      margin-top:15px;
      .el-icon-caret-bottom{font-size:12px;color:#666;cursor:pointer;}
    }
    .dialog_tags{
      &{width: 600px;}
      .el-input{margin-bottom:15px;}
    }
    .newattr_wrap{
      .el-dialog__body{text-align: center;}
      .el-input{width: 70%;margin-right: 10px;}
    }
  }
  .wx_fans_tag_pop{
    .el-tag{
      &{margin:0 10px 5px 0;width: 90px;position: relative;padding-right: 18px;overflow: hidden;text-overflow: ellipsis;}
      .el-icon-close{position:absolute;right:0;top:3px;}
    }
  }
</style>
